<?php

//绿保ecstore开通文档
ob_start();
set_time_limit(0);
define('ROOT_DIR',dirname(__FILE__));
define('APP_DIR',ROOT_DIR.'/app');
require(APP_DIR . '/base/kernel.php');
//autoload
if(!kernel::register_autoload()){
    require(APP_DIR . '/base/autoload.php');
}
//过滤get&post
if(get_magic_quotes_gpc()){
    kernel::strip_magic_quotes($_GET);
    kernel::strip_magic_quotes($_POST);
}

//验证是否安装
if(file_exists(kernel::single('base_setup_lock')->lockfile())){
    ob_end_clean();
    header("Content-type: application/json; charset=utf-8"); 
    $result['msg'] = '不能重复安装';
    $result['res'] = 'false';
    echo json_encode($result);
    exit;
}

//配置安装参数
$options = array(
    'base' => array(
                'db_host'=>$_POST['dbhost'],
                'db_user'=>$_POST['dbuser'],
                'db_password'=>$_POST['dbpass'],
                'db_name'=>$_POST['dbname'],
                'db_prefix'=>'sdb_'
              ),
    'desktop'=> array(
                'admin_uname'=>$_POST['userName'],
                'admin_password'=>$_POST['orig_passwd'],
                'admin_password_re'=>$_POST['orig_passwd'],
              ),
    'b2c'   => array(
                'demodata'=>($_POST['data']=='true')?1:0,            
              ),
);
unset($_POST);
unset($_GET);

//安装命令行
$shell = new base_shell_loader;
$config = base_setup_config::deploy_info();      
foreach($config['package']['app'] as $k=>$app){
    $applist[] = $app['id'];
}//需要安装的app
$install_queue = kernel::single('base_application_manage')->install_queue($applist, true);

//验证安装错误
foreach($install_queue as $app_id=>$app_info){
    $install_app[] = $app_id;
    if(false === app::get($app_id)->runtask('checkenv',$options[$app_id])){
        $error = true;
    }
}

//安装参数错误
if($error){
    //echo 'check env failed';
    $msg = ob_get_contents();
    ob_end_clean();
    header("Content-type: application/json; charset=utf-8"); 
    $result['msg'] = $msg;
    $result['res'] = 'false';
    echo json_encode($result);
    exit;
}else{
    //echo 'config init ok.';            
}

//开始安装
if(file_exists(ROOT_DIR.'/config/config.php')){
    kernel::set_online(true);
    $shell->input = $options;
    $shell->exec_command('install -r '.@join(' ', $install_app));
    //echo 'install success';
    ob_end_clean();
    header("Content-type: application/json; charset=utf-8"); 
    $result['msg'] = '安装成功';
    $result['res'] = 'true';
    echo json_encode($result);
    exit;
}else{
    //echo 'config file?';
    ob_end_clean();
    header("Content-type: application/json; charset=utf-8"); 
    $result['msg'] = '无法生成config文件';
    $result['res'] = 'false';
    echo json_encode($result);
    exit;
}

